import 'package:adaptive_dialog/adaptive_dialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:moment_dart/moment_dart.dart';
import 'package:spendbook/common/widgets.dart';
import 'package:spendbook/models/project.dart';

class AddFinanceScreen extends StatefulWidget {
  @override
  _AddFinanceScreenState createState() => _AddFinanceScreenState();
}

class _AddFinanceScreenState extends State<AddFinanceScreen> {
  Project project = new Project();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('添加理财项目'),
        actions: <Widget>[
          TextButton(
            style: Theme.of(context).useMaterial3 ? null : TextButton.styleFrom(foregroundColor: Theme.of(context).colorScheme.onPrimary),
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16),
            ),
            onPressed: () async {
              await project.store();
              Navigator.of(context).pop(project);
            },
          )
        ],
      ),
      body: FinanceStatefulWidget(
        project: project,
      ),
    );
  }
}

class SetFinanceScreen extends StatefulWidget {
  @override
  _SetFinanceScreenState createState() => _SetFinanceScreenState();
}

class _SetFinanceScreenState extends State<SetFinanceScreen> {
  Project? project;

  @override
  Widget build(BuildContext context) {
    if (project == null) {
      project = Project()..fromJson(ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>);
    }

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('修改理财项目'),
        actions: <Widget>[
          TextButton(
            child: Text(
              '提交',
              style: TextStyle(fontSize: 16),
            ),
            onPressed: () async {
              await project?.store();
              Navigator.of(context).pop(project);
            },
          )
        ],
      ),
      body: FinanceStatefulWidget(
        project: project!,
      ),
    );
  }
}

class ViewFinanceScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Project project = Project()..fromJson(ModalRoute.of(context)!.settings.arguments as Map<String, dynamic>);

    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        title: Text('理财项目'),
      ),
      body: FinanceStatefulWidget(
        project: project,
        readonly: true,
      ),
    );
  }
}

class FinanceStatefulWidget extends StatefulWidget {
  FinanceStatefulWidget({Key? key, required this.project, this.readonly = false}) : super(key: key);

  final Project project;

  final bool readonly;

  @override
  _FinanceStatefulWidgetState createState() => _FinanceStatefulWidgetState();
}

class _FinanceStatefulWidgetState extends State<FinanceStatefulWidget> {
  late Project _project;

  @override
  void initState() {
    super.initState();
    _project = widget.project;
  }

  @override
  Widget build(BuildContext context) {
    return PublicList(
      children: <Widget>[
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('项目名称'),
              ),
              Text(_project.name),
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入项目名称', textFields: [
              DialogTextField(initialText: _project.name),
            ]);
            if (res != null) {
              setState(() {
                _project.name = res.first;
              });
            }
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('金额'),
              ),
              Text(_project.fee.toStringAsFixed(2)),
              Text('元')
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入金额', textFields: [
              DialogTextField(
                  initialText: _project.fee > 0 ? _project.fee.toString() : '',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  validator: (val) => val!.isEmpty || double.tryParse(val) != null ? null : '请输入正确的金额'),
            ]);
            if (res != null) {
              setState(() {
                _project.fee = res.first;
              });
            }
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('年化率'),
              ),
              Text(_project.rate.toStringAsFixed(3)),
              Text('%')
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入收益率', textFields: [
              DialogTextField(
                  initialText: _project.rate > 0 ? _project.rate.toStringAsFixed(3) : '',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  validator: (val) => val!.isEmpty || double.tryParse(val) != null ? null : '请输入正确的收益率'),
            ]);
            if (res != null) {
              setState(() {
                _project.rate = res.first;
              });
            }
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('起始时间'),
              ),
              Text(_project.scopeTime),
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final DateTimeRange? picked = await showDateRangePicker(context: context, locale: Locale('zh'), firstDate: Moment.now().subtract(Duration(days: 365)).date, lastDate: DateTime(2099));
            if (picked != null) {
              setState(() {
                _project.startTime = Moment(picked.start);
                _project.endTime = Moment(picked.end);
              });
            }
          },
        ),
        ListTileScope(
          readonly: widget.readonly,
          title: Row(
            children: <Widget>[
              Expanded(
                child: Text('预计收益'),
              ),
              Text(_project.income.toStringAsFixed(2)),
              Text('元')
            ],
          ),
          trailing: Icon(Icons.chevron_right),
          onTap: () async {
            final res = await showTextInputDialog(context: context, title: '请输入预计收益', textFields: [
              DialogTextField(
                  initialText: _project.income > 0 ? _project.income.toStringAsFixed(2) : '',
                  keyboardType: TextInputType.numberWithOptions(decimal: true),
                  validator: (val) => val!.isEmpty || double.tryParse(val) != null ? null : '请输入正确的预计收益'),
            ]);
            if (res != null) {
              setState(() {
                _project.income = res.first;
              });
            }
          },
        ),
      ],
    );
  }
}
